package com.bang.concurrency.example.count;

import com.bang.concurrency.annotations.NotThreadSafe;
import com.bang.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther: Bang
 * @Date: 2019/9/29 22:21
 * @Description:
 */
@Slf4j
@NotThreadSafe
public class CountExample {

    // 同时并发执行的线程数
    private static int threadCount = 200;

    // 请求总数
    private static int clientCount = 5000;

    private static long count = 0;


    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadCount);
        CountDownLatch countDownLatch = new CountDownLatch(clientCount);
        for (int index = 0; index < clientCount; index++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.error("count = {}", count);
    }

    private static  void add() {
        count++;
    }
}
